package dm.ast;

import dm.ast.pro.DmCastFun;
import test.envset.GlobalState;

import java.util.ArrayList;
import java.util.List;

/***
 * @description:
 * Dm的子查询
 * 可以用作查询的From子句
 * 也可用作表达式
 * @author: scy
 * @date: 2024/4/16
 */
public class DmSubSelect extends DmTableSource{
    public DmSelect s = null;

    //todo
    //需要解决select的中查询列，与表中列的转化关系


    public DmSubSelect() {
        isSubSelect = true;
    }

    public DmSubSelect(DmSelect s) {
        this.s = s;
        setComplexity();
    }

    @Override
    public void fill(GlobalState globalState) {
        if(!isCompleted){
            s.fill(globalState);
            //别名已经在From子句构造完成
            //构造查询列
            buildColumns(globalState);
            isSubSelect = true;
        }
    }

    //构造查询列
    public void buildColumns(GlobalState globalState){
        cols = new ArrayList<DmColumn>();
        List<DmExpression> elements = s.getSelectElements().elements;
        for (int i = 0; i < elements.size(); i++) {
            DmExpression ele = elements.get(i);
            String colname = globalState.colAlias();
            DmColumn col = new DmColumn(colname, ele.reType);

            DmColumn col1 = null;
            if(ele.expLeft== null && !(ele instanceof  DmCase) && !(ele instanceof DmCastFun)){
                col1 = (DmColumn) ele;
                col.originalname = col1.name;
            }else{
                if(ele.expRight == null && (ele.expLeft instanceof DmColumn)){
                    col1 = (DmColumn) ele.expLeft;
                    col1.originalname = col1.name;
                }
            }
            ele.setSelEleAlias(colname);
            cols.add(col);
        }
    }

    @Override
    public void setWidt() {
        if(s == null){
            wid_t = 1;
        }else {
            s.setWidt();
            wid_t = s.wid_t;
        }

    }

    @Override
    public void setDept() {
        if(s == null){
            dep_t = 1;
        }else {
            s.setDept();
            dep_t = s.dep_t + 1;
        }
    }

    @Override
    public DmDataType getExpressionType() {
        return null;
    }

    @Override
    public void addColumn(DmColumn col) {
        //todo
    }

    public String toSql(){
        if(s == null){
            return " " + this.getClass().getSimpleName() + getSqlTarget();
        }else {
            if(alias != null){
                return String.format(" ((%s) %s%s)" , s.toSql() , alias , getSqlTarget());
            }else {
                return String.format(" ((%s)%s)" , s.toSql() , getSqlTarget());
            }
        }
    }

    //处理sql错误
    //-4097|单行子查询返回多行
    public void fixErr4097(){
        if(s != null){
            s.fixErr4097();
        }
    }
}
